// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: qiang

#include "coin2/exchange/crypto_v1/api_order/native_rest_async_asio_subscriber.h"

#include <glog/logging.h>

#include "coin2/exchange/crypto_v1/api_order/native_private_client.h"
#include "coin2/exchange/order/crypto.pb.h"
namespace coin2::exchange::crypto_v1::api_order {

void CryptoRestAsyncAsioSubscriber::QueryBalance() {
  auto http_context = rest_client()->QueryAccountBalance();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CryptoRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CryptoRestAsyncAsioSubscriber::QueryOpenOrders() {
  auto http_context = rest_client()->QueryOpenOrders();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CryptoRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CryptoRestAsyncAsioSubscriber::QueryHistOrders() {
  RestParams params;
  params.set_start_time(std::to_string(GetCurrentTimestamp() - kOneSecToNs * 60));
  params.set_end_time(std::to_string(GetCurrentTimestamp()));
  auto http_context = rest_client()->QueryHistOrders(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CryptoRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CryptoRestAsyncAsioSubscriber::QueryTrades() {
  RestParams params;
  params.set_start_time(std::to_string(GetCurrentTimestamp() - kOneSecToNs * 60));
  params.set_end_time(std::to_string(GetCurrentTimestamp()));
  auto http_context = rest_client()->QueryTrades(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CryptoRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CryptoRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&CryptoRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance",
      1);

  AddPeriodicTask(
      std::bind(&CryptoRestAsyncAsioSubscriber::QueryOpenOrders, this),
      config_.query_open_orders_period_sec(),
      "query_open_orders",
      2);

  AddPeriodicTask(
      std::bind(&CryptoRestAsyncAsioSubscriber::QueryHistOrders, this),
      config_.query_cancel_orders_period_sec(),
      "query_hist_orders",
      3);

  AddPeriodicTask(
      std::bind(&CryptoRestAsyncAsioSubscriber::QueryTrades, this),
      config_.query_fill_period_sec(),
      "query_fills",
      4);
}

}  // namespace coin2::exchange::crypto_v1::api_order
